from sys import argv, executable
from os import system
from os.path import exists, abspath, dirname
from base64 import b64encode
from typing import Optional

def encode_file(file_name):
    with open(file_name, "rb") as read_file:
        return b64encode(read_file.read()).decode()
def write_into_resource(file_name, content):
    with open(file_name, "a+") as write_file:
        write_file.write(f"ICON_DATA = '''{content}'''\n")
def cn_bash_mode():
    file = input("请选择ICON文件（默认为当前文件夹下的Logo.ico）：")
    if file == "":
        file = "Logo.ico"
    if not exists(file):
        print("文件不存在")
        cn_bash_mode()
    else:
        b64code = encode_file(file)
        source_file = input("请选择main.py中导入的资源文件（默认为当前文件夹下的resource.py）：")
        if source_file == "":
            source_file = "resource.py"
        elif not source_file.endswith(".py"):
            choose = input("正常来说文件末尾应当是.py，而现在你没有使用.py\n是否要自动添加.py【Y（默认）/N】")
            if choose.lower() != "n":
                source_file += ".py"
        write_into_resource(source_file, b64code)
def en_bash_mode():
    file = input("Please select the ICON file (default is Logo.ico in the current folder):")
    if file == "":
        file = "Logo.ico"
    if not exists(file):
        print("File does not exist")
        en_bash_mode()
    else:
        b64code = encode_file(file)
        source_file = input("Please select the resource file imported in main.py (default is resource.py in the current folder):")
        if source_file == "":
            source_file = "resource.py"
        elif not source_file.endswith(".py"):
            choose = input("Normally, the file suffix should be .py, but now you don't use .py\nDo you want to automatically add .py【Y（default）/N】")
            if choose.lower() != "n":
                source_file += ".py"
        write_into_resource(source_file, b64code)
def bash_mode(lang : Optional[str] = None):
    if not lang:
        lang = input("输入cn来使用中文\nEnter 'en' to use English\n请选择语言\tplease select language：")
    elif lang not in ["cn", "en"]:
        print("Invalid language\t无效的语言\nUse cn or en to select language\t使用cn或en来选择语言")
        return
    if lang == "en":
        en_bash_mode()
        print("Output completed")
        system("pause")
    else:
        cn_bash_mode()
        print("输出完成")
        system("pause")

def cn_gui_mode():
    from tkinter.messagebox import showinfo, showerror
    from tkinter.filedialog import askopenfilename, asksaveasfilename
    showinfo(title="提示", message="请在文件选择窗口中选择你的ICON图标")
    file = askopenfilename(title="选择图标", filetypes=[("ICON文件", "*.ico")], initialdir=dirname(abspath(__file__)), initialfile="Logo.ico")
    if not file:
        showerror(title="错误", message="用户单击了取消，程序退出")
        quit(114514)
    showinfo(title="提示", message="请选择main.py中导入的资源文件（一般情况下默认即可）")
    b64code = encode_file(file)
    source_file = asksaveasfilename(title="保存输出后的文件", filetypes=[("Python文件", "*.py"), ("所有文件", "*")], initialfile="resource.py", initialdir=dirname(abspath(__file__)), confirmoverwrite=False)
    write_into_resource(source_file, b64code)
def en_gui_mode():
    from tkinter.messagebox import showinfo, showerror
    from tkinter.filedialog import askopenfilename, asksaveasfilename
    showinfo(title="prompt", message="Please select your ICON icon in the file selection window")
    file = askopenfilename(title="Select Icon", filetypes=[("ICON file", "*.ico")], initialdir=dirname(abspath(__file__)), initialfile="Logo.ico")
    if not file:
        showerror(title="Error", message="User clicked Cancel, program exit")
        quit(114514)
    showinfo(title="prompt", message="Please select the resource file imported in main.py (usually default)")
    b64code = encode_file(file)
    source_file = asksaveasfilename(title="Save output file", filetypes=[("Python file", "*.py"), ("All files", "*")], initialfile="resource.py", initialdir=dirname(abspath(__file__)), confirmoverwrite=False)
    write_into_resource(source_file, b64code)


def gui_mode(lang : Optional[str] = None):
    from tkinter import dialog, Tk
    root = Tk()
    root.withdraw()
    if not lang:
        lang = dialog.Dialog(root, title="请选择语言 please select language：", text="请选择语言\nplease select language：", bitmap="question", strings=["中文", "英文"], default=0, parent=None)
    elif lang not in ["cn", "en"]:
        print("Invalid language\t无效的语言\nUse cn or en to select language\t使用cn或en来选择语言")
        return
    if lang == "en" or lang.num == 1:
        en_gui_mode()
        print("Output completed")
        system("pause")
    else:
        cn_gui_mode()
        print("输出完成")
        system("pause")

if len(argv) <=1:
    mode = input("输入 GUI 启动 图形模式\tEnter GUI to start graphic mode\n输入 BASH 启动 命令行模式\tEnter BASH startup command line mode\n请输入模式\tPlease enter the mode：").lower()
    if mode == "gui":
        gui_mode()
    elif mode == "bash":
        bash_mode()
    else:
        print("Invalid mode\t无效的模式\nThe mode should be between GUI and BASH\t模式应该介于 GUI 和 BASH")
        system("pause")
else:
    if len(argv)>=3:
        if argv[-1].lower() not in ["cn", "en"]:
            print("Invalid language\t无效的语言\nUse cn or en to select language\t使用cn或en来选择语言")
            quit(114514)
        else:
            if argv[-1].lower() == "cn":
                language = "cn"
            else:
                language = "en"
    else:
        language = "cn"
    if argv[1].lower() not in ["help", "gui", "bash", "img"]:
        print("Invalid mode\t无效的模式\nUse 'help' command to get more information\t使用help命令来获取更多帮助")
    else:
        if argv[1].lower() == "help":
            if language == "en":
                print(f"""
                      ICON打包工具

                      Usage:

                      {executable} {argv[0]} [mode] [file] [language]

                      mode：

                      help：show help

                      gui：graphic mode

                      bash：command line mode

                      img：followed by image file path, not filled in by default, defaults to Logo.ico

                      language:

                      cn：中文（default)

                      en: English
               """)

            else:
                print(f"""
                      ICON打包工具

                      使用方法：

                      {executable} {argv[0]} [mode] [file] [language]

                      mode：

                      help：显示帮助

                      gui：图形模式

                      bash：命令行模式

                      img：后面尾随图片文件路径，不填默认为Logo.ico
                      
                      language:

                      cn：中文(默认)

                      en: English
                """)
        if argv[1].lower() == "bash":
            bash_mode(language)